﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Portal.Core;
using System.Collections.ObjectModel;
using Portal.Web.Global;
using Portal.Web.Framework;
using System.Data;
using Portal.AssetTn.Model;

namespace Portal.Gui.Web.WebParts.AssetTn
{
    public class AssetRenderSearchBll
    {
        public static string Render(
            string SessionId,
            string Id,
            string FromWebPartId,
            string SiteId, 
            string AssetTypeId,
            string Subject,
            string AssetTypeImage,
            bool   VisibleTitle)
        {
            try
            {
                AjaxPro.Utility.RegisterTypeForAjax(typeof(AssetRenderSearchBll));
                ParamCls[] ItemsSearchParams = AssetViewFieldBll.GetSearchParams(SiteId, AssetTypeId);
                Collection<ParamCls> SearchParams = new Collection<ParamCls> { };
                for (int iIndex = 0; iIndex < ItemsSearchParams.Length; iIndex++)
                {
                    SearchParams.Add(ItemsSearchParams[iIndex]);
                }
                if (SearchParams.Count % 2 != 0) SearchParams.Add(null);
               
                string RetHtml =
                        " <script language=javascript>\r\n" +
                        "   function ClientResetSearch()\r\n" +
                        "   {\r\n" +
                        "       if(confirm('Bạn đã chắc chắn xóa điều kiện tìm kiếm chưa?')==false)return;\r\n";
                for (int iIndex = 0; iIndex < ItemsSearchParams.Length; iIndex++)
                {
                    RetHtml += "  document.getElementById('txtSearchField" + ItemsSearchParams[iIndex].Key + "').value='';\r\n";
                }
                RetHtml +=
                        "   }\r\n" +
                        "   function SearchNextPage(CurrentPageIndex)\r\n" +
                        "   {\r\n" +
                        "       document.getElementById('txtSearchPageIndex').value=CurrentPageIndex;\r\n" +
                        "       document.getElementById('divProcessing').innerHTML='Đang tìm kiếm dữ liệu trên máy chủ dịch vụ...';\r\n" +
                        "       setTimeout('RealClientSearch()',10);\r\n" +
                        "   }\r\n" +

                        "   function ClientSearch(Print)\r\n" +
                        "   {\r\n" +
                        "       document.getElementById('divProcessing').innerHTML='Đang tìm kiếm dữ liệu trên máy chủ dịch vụ...';\r\n" +
                        "       setTimeout('RealClientSearch('+Print+')',10);\r\n" +
                        "   }\r\n" +

                        "   function RealClientSearch(PrintOption)\r\n" +
                        "   {\r\n" +
                        "       SessionId='"+SessionId+"';\r\n"+
                        "       SiteId='" + SiteId + "';\r\n" +
                        "       AssetTypeId='"+AssetTypeId+"';\r\n"+
                        "       Max=" + ItemsSearchParams.Length + ";\r\n" +
                        "       PageIndex = parseInt(document.getElementById('txtSearchPageIndex').value);\r\n" +
                        "       SortField='SortInventoryNumber';\r\n"+//document.getElementById('drpSelectSortField').value;\r\n" +
                        "       SortType='ASC';\r\n"+//document.getElementById('drpSelectSortType').value;\r\n" +
                        "       AjaxOut=Portal.Gui.Web.WebParts.AssetTn.AssetRenderSearchBll.ServerSideGetParam(SiteId,AssetTypeId).value;\r\n" +
                        "       if(AjaxOut.Error)\r\n" +
                        "       {\r\n" +
                        "           alert(AjaxOut.InfoMessage);\r\n" +
                        "           return;\r\n" +
                        "       }\r\n" +
                        "       Params=AjaxOut.RetObject;\r\n" +
                        "       for(var iIndex=0;iIndex<Max;iIndex++)\r\n" +
                        "       {\r\n" +
                        "           Ids='txtSearchField'+Params[iIndex].Key;\r\n" +
                        "           v=document.getElementById(Ids).value;\r\n" +
                        "           Params[iIndex].Value=v;\r\n" +
                        "       }\r\n" +
                        "       LoadFromBackEnd= document.getElementById('txtLoadFromBackEnd').value;\r\n" +
                        "       AjaxOut = Portal.Gui.Web.WebParts.AssetTn.AssetRenderSearchBll.ServerSideSearch(SiteId, SessionId, AssetTypeId, LoadFromBackEnd, Params, PrintOption, SortField, SortType, PageIndex).value;\r\n" +
                        "       document.getElementById('divProcessing').innerHTML='';\r\n" +
                        "       if(AjaxOut.Error)\r\n" +
                        "       {\r\n" +
                        "           alert(AjaxOut.InfoMessage);\r\n" +
                        "           return;\r\n" +
                        "       }\r\n" +
                        "       if(AjaxOut.RetLink)\r\n"+
                        "       {\r\n"+
                        "           window.open(AjaxOut.RetUrl,'_self');\r\n" +
                        "       }\r\n"+
                        "       else\r\n"+
                        "       {\r\n"+
                        "           document.getElementById('divSearchResult').innerHTML=AjaxOut.HtmlContent;\r\n" +
                        "           window.open('Go.aspx?wpid="+FromWebPartId+"#divSearchResult','_self');\r\n" +
                        "           document.getElementById('divSearchForm').style.display='none';\r\n" +
                        "           document.getElementById('buttonSearch').value='Hiện cửa sổ tìm kiếm';\r\n" +
                        "       }\r\n"+
                        "   }\r\n" +

                        "   function ClientShowHidenSearchForm()\r\n" +
                        "   {\r\n" +
                        "       if(document.getElementById('divSearchForm').style.display=='block')\r\n" +
                        "       {\r\n" +
                        "           document.getElementById('divSearchForm').style.display='none';\r\n" +
                        "           document.getElementById('buttonSearch').value='Hiện cửa sổ tìm kiếm';\r\n" +
                        "       }\r\n" +
                        "       else\r\n" +
                        "       {\r\n" +
                        "           document.getElementById('divSearchForm').style.display='block';\r\n" +
                        "           document.getElementById('buttonSearch').value='Ẩn cửa sổ tìm kiếm';\r\n" +
                        "       }\r\n" +
                        "   }\r\n" +

                        " </script>\r\n" +
                        " <div id=\"" + Id + "\"> \r\n" +
                        " <input id=txtLoadFromBackEnd value=\"0\" type=\"hidden\">\r\n" +
                        " <input id=txtSearchPageIndex value=\"0\" type=hidden>\r\n" +
                        " <table class=\"il_Block\" datatable=\"0\">\r\n" +
                        " <tbody>\r\n";
                if (VisibleTitle)
                {
                    RetHtml +=
                        " <tr>\r\n" +
                        "     <td class=\"ilBlockHeaderBig\" colspan=\"1\">\r\n" +
                        "       <div style=\"float:left;\">\r\n" +
                        "         <h3 class=\"ilBlockHeader\"><a class=\"ilAccAnchor\" name=\"" + Id + "_blhead\" id=\"" + Id + "_blhead\">" + Subject + "</a></h3> <span id=\"" + Id + "_loader\"></span>\r\n" +
                        "       </div>\r\n" +
                        "     </td>\r\n" +
                        " </tr>\r\n";
                }

                RetHtml +=
                        "   <tr class=\"tblrow1\">\r\n" +
                        "       <td class=\"std\"><div style=\"float:right;\"><img style=\"width:100px;\" border=\"0\" src=\"./templates/default/images/" + AssetTypeImage + "\"></div>\r\n" +
                        "       <h1>" + Subject + "<input type=button class=button style=\"float:right\" value=\"Ẩn cửa sổ tìm kiếm\" id=buttonSearch onclick=\"javascript:ClientShowHidenSearchForm();\"></h1>\r\n" +
                        "           <p>Để tìm kiếm theo tiêu chí nào nhập liệu vào ô tìm kiếm đó. Để trắng nếu muốn loại bỏ phạm vi tìm kiếm này:</p>\r\n" +
                        "           <div id=divSearchForm style=\"display:block\" class=CssFormSaveUpdate>\r\n" +
                        "           <table class=AdvanceSearchTable>\r\n";
                int IndexRecord = 0;
                while (true)
                {
                    string SelectLookUp = AssetUtility.GetLookUp(SiteId, SearchParams[IndexRecord].Key,"txtSearchField", SearchParams[IndexRecord].Value);
                    RetHtml += "<tr>\r\n";
                    if (!string.IsNullOrEmpty(SelectLookUp))
                    {
                        RetHtml +=
                               "      <td class=c1>" + SearchParams[IndexRecord].Title + "</td>\r\n" +
                               "      <td class=c2>" + SelectLookUp + "</td>\r\n";
                    }
                    else
                    {
                        RetHtml +=
                               "      <td class=c1>" + SearchParams[IndexRecord].Title + "</td>\r\n" +
                               "      <td class=c2><input id=\"txtSearchField" + SearchParams[IndexRecord].Key + "\" type=textbox class=textbox></td>\r\n";
                    }
                   
                    IndexRecord = IndexRecord + 1;
                    if (IndexRecord == SearchParams.Count)
                    {
                        RetHtml +=
                               "      <td class=c1></td>\r\n" +
                               "      <td class=c2></td>\r\n";
                        break;
                    }
                    if (SearchParams[IndexRecord] != null)
                    {
                        SelectLookUp = AssetUtility.GetLookUp(SiteId, SearchParams[IndexRecord].Key, "txtSearchField", SearchParams[IndexRecord].Value);
                        if (!string.IsNullOrEmpty(SelectLookUp))
                        {
                            RetHtml +=
                                   "      <td class=c1>" + SearchParams[IndexRecord].Title + "</td>\r\n" +
                                   "      <td class=c2>" + SelectLookUp + "</td>\r\n";
                        }
                        else
                        {
                            RetHtml +=
                                   "      <td class=c1>" + SearchParams[IndexRecord].Title + "</td>\r\n" +
                                   "      <td class=c2><input id=\"txtSearchField" + SearchParams[IndexRecord].Key + "\" type=textbox class=textbox></td>\r\n";
                        }
                    }
                    else
                    {
                        RetHtml +=
                               "      <td class=c1></td>\r\n" +
                               "      <td class=c2></td>\r\n";
                    }
                    RetHtml +=
                               "  </tr>\r\n";
                    IndexRecord++;
                    if (IndexRecord == SearchParams.Count) break;
                }

                string SelectSortType = "Kiếu sắp: <select class=\"drplist\" id=drpSelectSortType>\r\n" +
                                        "       <option value=\"ASC\">Sắp xếp tăng</option>\r\n" +
                                        "       <option value=\"DESC\">Sắp xếp giảm</option>\r\n" +
                                        "</select>\r\n";

                //string SelectSortField =
                //                       "Trường sắp: <select class=\"drplist\" id=drpSelectSortField>\r\n" +
                //                       "       <option value=\"SortInventoryNumber\">Số thứ tự</option>\r\n" +
                //                       "       <option value=\"ClassCode\">Số phân loại</option>\r\n" +
                //                       "       <option value=\"ProfileCode\">Số hồ sơ</option>\r\n" +
                //                       "       <option value=\"InventoryCode\">Số xếp kho</option>\r\n" +
                //                       "       <option value=\"Subject\">Tiêu đề</option>\r\n" +
                //                       "</select> \r\n";
                //RetHtml += "  <tr>\r\n" +
                //           "      <td class=c1></td>\r\n" +
                //           "      <td class=c2 colspan=3>\r\n" +
                //                    SelectSortField+SelectSortType +
                //           "      </td>\r\n"+
                //           "  </tr>\r\n"+
                RetHtml+=
                           "  <tr>\r\n" +
                           "      <td class=c1></td>\r\n" +
                           "      <td class=c2 colspan=3>\r\n"+
                           "             <input type=button class=button value=\"Tìm kiếm\" onclick=\"javascript:ClientSearch(0);\">\r\n"+
                           "             <input type=button class=button value=\"Tìm kiếm & in ấn\" onclick=\"javascript:ClientSearch(1);\">\r\n" +
                           "             <input type=button class=button value=\"Điều kiện tìm kiếm mới\" onclick=\"javascript:ClientResetSearch();\">\r\n"+
                           "             </td>\r\n" +
                           "  </tr>\r\n";

                RetHtml += "</table>\r\n";
                RetHtml +=

                        "           <ul>\r\n" +
                        "               <li>Các từ khóa tìm kiếm cần có độ dài > 3 và có ý nghĩa. Các từ khóa này sẽ được lưu lại thông kê đưa vào các từ khóa thường xuyên tìm kiếm</li>\r\n" +
                        "               <li>Trong trường hợp bạn cần tìm kiếm đơn giản hơn có thể chuyển sang tìm kiếm đơn giản. Với chức năng tìm kiếm đơn giản hệ thống sẽ tìm kiếm nhanh chóng với kết quả gần nhất</li>\r\n" +
                        "               <li>Trong trường hợp tìm được kết quả bạn có thể xem chi tiết hiện vật, chỉnh sửa, xóa hiện vật đó nếu như có quyền truy cập đến chức năng này</li>\r\n" +
                        "           </ul>\r\n" +
                        "       </td>\r\n" +
                        "   </tr>\r\n" +
                        "  </tbody>\r\n" +
                        "</table>\r\n" +
                        "</div>\r\n" +
                        "</div>\r\n" +
                        "<div id=divProcessing></div>\r\n" +
                        "<div id=divSearchResult>\r\n" +
                        "</div>\r\n";

                return RetHtml;
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
        }


        [AjaxPro.AjaxMethod]
        public AjaxReturn ServerSideGetParam(string SiteId,string AssetTypeId)
        {
            AjaxReturn oAjaxReturn = new AjaxReturn();

            try
            {
                oAjaxReturn.RetObject = AssetViewFieldBll.GetSearchParams(SiteId, AssetTypeId);
            }
            catch (Exception ex)
            {
                oAjaxReturn.Error = true;
                oAjaxReturn.InfoMessage = ex.Message.ToString();
            }
            return oAjaxReturn;
        }



        [AjaxPro.AjaxMethod]
        public AjaxReturn ServerSideSearch(
            string SiteId,
            string SessionId,
            string AssetTypeId,
            string LoadFromBackEnd,
            ParamCls[] Params,
            int PrintOption,
            string SortField, 
            string SortType,
            int CurrentPageIndex)
        {
            AjaxReturn oAjaxReturn = new AjaxReturn();
            try
            {
                //doan nay tim kiem
                Environments.CheckSessionTimeOut(true);
                DataSet dsResult = null;
                AssetModel[] AssetModels = AssetBll.Search(SiteId, AssetTypeId, Params, null,SortField,SortType, ref dsResult);                
                AssetSearchResult oAssetSearchResult = AssetBll.WebRenderResult(SiteId, int.Parse(LoadFromBackEnd), AssetModels, CurrentPageIndex);
                oAjaxReturn.HtmlContent =
                    PortalRenderBll.GetPorletFromTemplate(SiteId, "AdvanceSearch", "Kết quả tìm kiếm (" + oAssetSearchResult.TotalRecord.ToString("#,##0") + "), tổng số hiện vật là (" + oAssetSearchResult.TotalAsset.ToString("#,##0") + ")", oAssetSearchResult.HtmlContent).HtmlContent;
                if (PrintOption==1)
                {
                    oAjaxReturn.RetLink=true;

                    if (dsResult.Tables.Count == 0) throw new Exception("Không tìm thấy hiện vật thỏa mãn điều kiện in sổ!");
                    dsResult.Tables[0].TableName = "TableAssetList";
                    dsResult.DataSetName = "TableAssetList";
                    ReportServiceBll.SaveData(SiteId, Environments.CurrentLoginUser.LoginName, dsResult, SessionId);
                    oAjaxReturn.RetUrl = "Print.aspx?wpid=AssetTN.PrintAssetListOption&SessionId=" + SessionId;                    
                }
            }
            catch (Exception ex)
            {
                oAjaxReturn.Error = true;
                oAjaxReturn.InfoMessage = ex.Message.ToString();
            }
            return oAjaxReturn;
        }

        public static string GetValue(AssetModel OAssetModel, string Key)
        {
            if(Key.ToLower().Equals("AssetListId".ToLower()))return OAssetModel.AssetListId;
            if(Key.ToLower().Equals("AssetStatus".ToLower()))return OAssetModel.AssetStatus;
            if(Key.ToLower().Equals("AssetStatusName".ToLower()))return OAssetModel.AssetStatusName;
            if(Key.ToLower().Equals("AssetType".ToLower()))return OAssetModel.AssetType;
            if(Key.ToLower().Equals("AssetTypeName".ToLower()))return OAssetModel.AssetTypeName;
            if(Key.ToLower().Equals("Avatar".ToLower()))return OAssetModel.Avatar;
            if(Key.ToLower().Equals("Characteristic".ToLower()))return OAssetModel.Characteristic;
            if(Key.ToLower().Equals("ClassCode".ToLower()))return OAssetModel.ClassCode;
            if(Key.ToLower().Equals("ContentHistory".ToLower()))return OAssetModel.ContentHistory;
            if(Key.ToLower().Equals("Cost".ToLower()))return OAssetModel.Cost;
            if(Key.ToLower().Equals("DeliverBy".ToLower()))return OAssetModel.DeliverBy;
            if(Key.ToLower().Equals("Description".ToLower()))return OAssetModel.Description;
            if(Key.ToLower().Equals("EntryDate".ToLower()))return OAssetModel.EntryDate;
            
            if(Key.ToLower().Equals("frkAssetStatusId".ToLower()))return OAssetModel.frkAssetStatusId;
            if(Key.ToLower().Equals("frkAssetTypeId".ToLower()))return OAssetModel.frkAssetTypeId;
            if (Key.ToLower().Equals("frkAssetMaterialId".ToLower())) return OAssetModel.frkAssetMaterialId;
            if (Key.ToLower().Equals("frkAssetNationalId".ToLower())) return OAssetModel.frkAssetNationalId;
            
            if(Key.ToLower().Equals("Icon".ToLower()))return OAssetModel.Icon;
            if(Key.ToLower().Equals("InventoryCode".ToLower()))return OAssetModel.InventoryCode;
            if(Key.ToLower().Equals("MadeBy".ToLower()))return OAssetModel.MadeBy;
            if(Key.ToLower().Equals("MadePlace".ToLower()))return OAssetModel.MadePlace;
            if(Key.ToLower().Equals("Material".ToLower()))return OAssetModel.Material;
            if(Key.ToLower().Equals("Note".ToLower()))return OAssetModel.Note;
            if(Key.ToLower().Equals("OtherSubject".ToLower()))return OAssetModel.OtherSubject;
            if(Key.ToLower().Equals("ProfileCode".ToLower()))return OAssetModel.ProfileCode;
            if(Key.ToLower().Equals("Quantity".ToLower()))return OAssetModel.Quantity;
            if(Key.ToLower().Equals("RegDate".ToLower()))return OAssetModel.RegDate;
            if(Key.ToLower().Equals("Report".ToLower()))return OAssetModel.Report;
            if(Key.ToLower().Equals("Size".ToLower()))return OAssetModel.Size;
            if(Key.ToLower().Equals("StoragePlace".ToLower()))return OAssetModel.StoragePlace;
            if(Key.ToLower().Equals("Subject".ToLower()))return OAssetModel.Subject;
            if(Key.ToLower().Equals("TechnicalMade".ToLower()))return OAssetModel.TechnicalMade;
            if(Key.ToLower().Equals("UseFor".ToLower()))return OAssetModel.UseFor;
            
            if (Key.ToLower().Equals("InventoryNumber".ToLower())) return OAssetModel.InventoryNumber;
            if (Key.ToLower().Equals("ReceiveBy".ToLower())) return OAssetModel.ReceiveBy;
            if (Key.ToLower().Equals("CollectCode".ToLower())) return OAssetModel.CollectCode;
            if (Key.ToLower().Equals("MadeDate".ToLower())) return OAssetModel.MadeDate;
            if (Key.ToLower().Equals("CollectDate".ToLower())) return OAssetModel.CollectDate;
            if (Key.ToLower().Equals("FicDescription".ToLower())) return OAssetModel.FicDescription;
            if (Key.ToLower().Equals("InputDate".ToLower())) return OAssetModel.InputDate;


            throw new Exception(Key+" not found");
        }
    }
}
